import json
import os

RESERVATIONS_FILE_PATH = "data/reservations.json"
LAYOUT_FILE_PATH = "data/layout.json"


def load_reservations_from_file():
    if not os.path.exists(RESERVATIONS_FILE_PATH):
        return []

    try:
        with open(RESERVATIONS_FILE_PATH, 'r', encoding='utf-8') as f:
            return json.load(f)
    except (json.JSONDecodeError, IOError):
        return []


def save_reservations_to_file(all_reservations_list):
    try:
        with open(RESERVATIONS_FILE_PATH, 'w', encoding='utf-8') as f:
            json.dump(all_reservations_list, f, indent=4, ensure_ascii=False)
        return True
    except IOError:
        print("保存预约数据时出错。")
        return False


def load_layout_config_from_file():
    if not os.path.exists(LAYOUT_FILE_PATH):
        # Return default layout if file doesn't exist
        return {
            "total_seats": 50,
            "seat_prefix": ["A", "B", "C", "D", "E"],
            "seats_per_prefix_row": 10,
            "timeslots": ["08:00-12:00", "14:00-18:00", "19:00-22:00"]
        }

    try:
        with open(LAYOUT_FILE_PATH, 'r', encoding='utf-8') as f:
            return json.load(f)
    except (json.JSONDecodeError, IOError):
        # Return default layout if file is corrupted
        return {
            "total_seats": 50,
            "seat_prefix": ["A", "B", "C", "D", "E"],
            "seats_per_prefix_row": 10,
            "timeslots": ["08:00-12:00", "14:00-18:00", "19:00-22:00"]
        }